# --------------------------------------------------------------------------------
#  NoiseTube Web application
#
#  Copyright (C) 2008-2010 SONY Computer Science Laboratory Paris
#  Portions contributed by Vrije Universiteit Brussel (BrusSense team), 2008-2011
# --------------------------------------------------------------------------------
#  This library is free software; you can redistribute it and/or modify it under
#  the terms of the GNU Lesser General Public License, version 2.1, as published
#  by the Free Software Foundation.
#
#  This library is distributed in the hope that it will be useful, but WITHOUT
#  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
#  FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
#  details.
#
#  You should have received a copy of the GNU Lesser General Public License along
#  with this library; if not, write to:
#    Free Software Foundation, Inc.,
#    51 Franklin Street, Fifth Floor,
#    Boston, MA  02110-1301, USA.
#
#  Full GNU LGPL v2.1 text: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt
#  NoiseTube project source code repository: http://code.google.com/p/noisetube
# --------------------------------------------------------------------------------
#  More information:
#   - NoiseTube project website: http://www.noisetube.net
#   - Sony Computer Science Laboratory Paris: http://csl.sony.fr
#   - VUB BrusSense team: http://www.brussense.be
# --------------------------------------------------------------------------------

require 'json'

class AjaxController < ApplicationController
  include Geokit::Geocoders
  include AuthenticatedSystem
  #caches_action :index, :layout=>false
  #caches_page :index

  respond_to :xml, :json
  before_filter :authenticate_user, :only => [:get_tags_html, :get_aggmap  ]

  def loadmap

    stored_cities = City.with_geodata
    #$.getJSON("/course_requests/new.json",...);
    render :json => ActiveSupport::JSON.encode(stored_cities)

  end

  def cityinfo
    city = City.find(params[:param])

    respond_with({
                     city: city.as_json(),
                     tracks: city.tracks.as_json(:only => [:avg_loudness, :created_at, :graph_image_url, :id, :maxloudness, :minloudness, :user_id, :track_comment]),
                     contributors: city.city_contributors(5).as_json(:include => {user: { only: [:id, :login, :phonemodel]}}),
                     tags: city.tags(10).as_json(:only => [:id, :tag_name, :context, :user_id, :created_at]),
                     has_map:  File.exist?("#{Rails.root}/public/kmz/city_#{city.id}.kmz"),
                     leq_image: leqdist_png({city: params[:param], size: "120x140"})
                 })
  end

  def get_tags_html
    track_id = params[:track]
    track_id = track_id.gsub(/track-/,"").to_i  unless track_id.nil?
    links = []

    track_tags = Track.find(track_id).popular_track_tags.all
    links = generate_tag_cloud(track_tags)  unless track_tags.blank?
    links = links.join(",")  unless links.blank?
    render text: links, status: "200 OK"
  end

  def get_trackmap
    track_id = params[:track]
    track_id = track_id.gsub(/trackmap-/,"").to_i  unless track_id.nil?

    track = Track.find(track_id)
    track_measures = track.geomeasures.all

    render :json => {track: track, measures: track_measures}.to_json(),
           status: "200 OK"
  end

  def measureinfo
    measure_id = params[:mid]
    measure = Measure.find(measure_id)
    render :json => measure.to_json
  end

  def tracklocation
    track = Track.find(params[:id])
    track.find_location
    track.save
  end

  def allcities
    @cities = City.order("name ASC").all
    thecities = []
    @cities.map!{|city|
      thecities << { label: city.name.gsub(/,/,""), id: city.id }
    }
    render :json => thecities , status: "200 OK"
  end

  #gets the aggregated map data
  def get_aggmap
    aggmap_id = params[:id]
    aggmap_id = aggmap_id.gsub(/aggmap-/,"").to_i  unless aggmap_id.nil?

    aggmap = AggregateMap.find(aggmap_id)
    aggmap_json = aggmap.json_text

    aggmap_json = "[]" if aggmap.json_text.blank?

    render :text => aggmap_json,
           status: "200 OK"
  end
  # -----------------------------------------------------

  private

  def authenticate_user
    unless logged_in?
      render text: "{error: 'error'}", status: "200 OK"
    end
  end

  # copied form TagsHelper, modified for this case
  def generate_tag_cloud(tags_clouds,tags_param="", category="user")   #category "tags"?

    links =  []
    unless tags_clouds.blank?
      #create the tag-cloud
      tag_cloud(tags_clouds, %w(size0 size1 size2 size3 size4)).map { |tag, css_class|
        url=tags_param.clone
        url= url << ("#{category}:#{tag.tag_name || "unnamed"}") << ","
        link= view_context.link_to("#{tag.tag_name || "unnamed"}", {:action => :filter, :controller => :tags, :tags => url}, :class => css_class, :title => "#{tag.count} measures")
        links << link
      }
    else
      #yield("no tag")
    end
    links
  end

  def tag_cloud(tags, s1)
    # zip em
    tags.blank?  ? [] :  tags.zip(s1)
  end
end

# -------------------------------------------------
private

#leqdist - note wont work for cartasur part
def leqdist_png(params)
  dist=Api.distribution_leq(params)

    # PNG RESPONSE
  graph= view_context.generate_leq_distribution_graph(dist,params)
  ret = graph
  ret
end
